package com.yc.qunxing.filter;

import com.yc.qunxing.config.GatewayConfig;
import com.yc.qunxing.context.BaseContext;
import com.yc.qunxing.properties.JwtProperties;
import com.yc.qunxing.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Slf4j
@RequiredArgsConstructor
public class JwtTokenUserFilter implements GlobalFilter, Ordered{

    {
        System.out.println("-------------JwtTokenUserFilter---------------");
    }


    @Autowired
    private final GatewayConfig gatewayConfig;

    private final AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();

        // 根据配置文件中的 excludePaths 判断是否要做拦截
        String path = request.getPath().value();
        if (isExclude(path)){
            // 放行
            return chain.filter(exchange);
        }
        // 从请求头中获取令牌
        String token = exchange.getRequest().getHeaders().getFirst(JwtProperties.adminTokenName);

        // 校验令牌
        try {
            System.out.println("JWT校验:"+token);

            Claims claims = JwtUtil.parseJWT(JwtProperties.adminSecretKey, token);
            return chain.filter(exchange);
        } catch (Exception ex) {
            // 不通过，返回401状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }
    // 判断请求路径是否需要被拦截，该路径在 excludePaths 中则说明不要被拦截，返回true
    private boolean isExclude(String path) {
        System.out.println("请求路径: " + path);
        System.out.println(gatewayConfig.getExcludePaths()+"aaaa");
        for (String pathPattern : gatewayConfig.getExcludePaths()) {
            // 判断 path 是否匹配 pathPattern
            if (antPathMatcher.match(pathPattern,path)){
                System.out.println("不拦截"+path+".........."+pathPattern);
                return true;
            }
        }
        System.out.println("拦截：" + path);
        return false;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
